package controller;

import helper.Formatter;
import helper.Postman;
import helper.Randomness;
import helper.UserSession;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import model.CustomerDAO;
import model.EmployeeDAO;
import model.Model;

public class EmployeeCreateCustomerAccountAction extends Action{
    private CustomerDAO customerDAO;

    public EmployeeCreateCustomerAccountAction(Model model) {
        customerDAO = model.getCustomerDAO();
    }
    
    public String getName() {
        return "employeeCreateCustomerAccount.do";
    }
    

    public String perform(HttpServletRequest request) {
        //ATTENTION
        // define target page
    	String loginPage = "employee/employee-login.jsp";
        String originPage = "employee/customer-manager.jsp";
        String successPage = originPage; 
        
        //set the employee
        Employee employee = null;
        Customer customer = null;

        //errors and messages will be stored here
        //resetting those containers
        List<String> errors = new ArrayList<String>();
        List<String> messages = new ArrayList<String>();
   
        //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        request.setAttribute("page", "cust-manager");
        
        try {
			Customer[] customers = customerDAO.getCustomers();
			request.setAttribute("customers", customers);
		} catch (DAOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
        //get all the parameter from the form
        
        String requestType = request.getParameter("Submit");
        String username = request.getParameter("txtUsername");
        String firstName = request.getParameter("txtFirstName");
        String lastName = request.getParameter("txtLastName");
        String addrLine1 = request.getParameter("txtAddrLine1");
        String addrLine2 = request.getParameter("txtAddrLine2");
        String city = request.getParameter("txtCity");
        String state = request.getParameter("txtState");
        String zip = request.getParameter("txtZip");
        String cash = request.getParameter("txtCash");
        String email = request.getParameter("txtEmail");
        //String password = request.getParameter("txtPassword");
        //String confirmPassword = request.getParameter("txtConfirmPassword");
        
        
        //reload the form field
        request.setAttribute("txtUsername", username);
        request.setAttribute("txtFirstName", firstName);
        request.setAttribute("txtLastName", lastName);
        request.setAttribute("txtAddrLine1", addrLine1);
        request.setAttribute("txtAddrLine2", addrLine2);
        request.setAttribute("txtCity", city);
        request.setAttribute("txtState", state);
        request.setAttribute("txtZip", zip);
        request.setAttribute("txtCash", cash);
        request.setAttribute("txtEmail", email);
        //request.setAttribute("txtPassword", username);
        //request.setAttribute("txtConfirmPassword", firstName);
        //password is not reloaded for obvious reason
        
        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        if (employee == null) {
            errors.add("You need to log in");
            request.setAttribute("page", "login");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }
        
        //validate if user has necessary qualification
        //check the session

        // check for get or post request
        //if there is no parameter get passed, return to origin page
        
        
        if (requestType == null) {
            //messages.add("To create employee account, fill the below form");
            return originPage;     
        }
         
        //validate the input
        if (firstName.trim().equals("")) {
            //messages.add("Enter customer first name");
            errors.add("First name cannot be blank. Please check.");
            return originPage;
        }
 
        if (lastName.trim().equals("")) {
            //messages.add("Enter customer last name");
            errors.add("Last name cannot be blank. Please check.");
            return originPage;
        }
        
        if (username.trim().equals("")) {
            //messages.add("Enter the desired username");
            errors.add("Username cannot be blank. Please check.");
            return originPage;
        }
        
        if (username.trim().length() < 4) {
            errors.add("Username entered is too short. Minimum length required is 8 characters.");
            return originPage;
        }
        
        if (email.trim().equals("")) {
            errors.add("Email cannot be blank. Please check.");
            return originPage;
        }
        
        if (!Formatter.isEmail(email)){
            //messages.add("Email format must be *@*.*");
            errors.add("Invalid email address format. Please check.");
            return originPage;
        }
        
        if (addrLine1.trim().equals("")) {
            //messages.add("Enter customer Address 1");
            errors.add("Address field  cannot be blank. Please check.");
            return originPage;
        }
        
        if (city.trim().equals("")) {
            //messages.add("Enter customer city");
            errors.add("City cannot be blank. Please check.");
            return originPage;
        }
        
        if (state.trim().equals("")) {
            //messages.add("Enter customer state");
            errors.add("State field cannot be blank. Please check.");
            return originPage;
        }
        
        if (zip.trim().equals("")) {
            errors.add("Zip cannot be blank. Please check.");
            return originPage;
        }
        
        /* Password should be autogenerated so no use of taking input from form.
        if (password.trim().equals("")) {
            messages.add("Enter the desired password");
            errors.add("Current password field is still empty");
            return originPage;
        }

        if (confirmPassword.trim().equals("")){
            messages.add("Enter confirmation password");
            errors.add("Confirmation password field is still empty");
            return originPage;
        }
        
        if (!confirmPassword.trim().equals(password.trim())){
            messages.add("Both new password and confirmation password must be the same");
            errors.add("Both password and confirmation password you have supplied are different");
            return originPage;
        }*/
        

        
        // at this stage, all validation should have been done
        try {
            
            customer = customerDAO.lookup(username);
            
            //check if customer username ie is unique
            if (customer!=null){
                errors.add("Username already exist. Pleae choose another username");
                return originPage;
            }
            
            //Cash will always start from 0.0
            cash = "0.0000";
            
            //password is randomly generated
            String randomPassword = "randomPassword";
            randomPassword = Randomness.randomPassword();
            
            //create employee object
            customer = new Customer();
            customer.setUsername(username);
            customer.setFirstName(firstName);
            customer.setLastName(lastName);
            customer.setPassword(randomPassword);
            customer.setAddrLine1(addrLine1);
            customer.setAddrLine2(addrLine2);
            customer.setCity(city);
            customer.setState(state);
            customer.setZip(zip);
            customer.setCash( Formatter.prepCashFromView(cash));
            customer.setEmail(email);
            
            //crete employee into database
            customerDAO.create(customer);
            
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            Employee loggedInEmployee = UserSession.getLoggedInEmployee(request);
            session.setAttribute("employee", loggedInEmployee );
            
            //email mechanism here
            Postman.sendCreateCustomerConfirmation(customer, randomPassword);

            //set the welcome message
            //messages.add("Hi " + loggedInEmployee.getFirstName() + "!");
            messages.add("Succesfully created customer with username: <b>" + customer.getUsername() + "</b> and password <b>" + randomPassword +"</b>.");
            messages.add("Confirmation email has been sent to: <b>" + customer.getEmail() + "</b>");
            
            request.setAttribute("txtUsername", "");
            request.setAttribute("txtFirstName", "");
            request.setAttribute("txtLastName", "");
            request.setAttribute("txtAddrLine1", "");
            request.setAttribute("txtAddrLine2", "");
            request.setAttribute("txtCity", "");
            request.setAttribute("txtState", "");
            request.setAttribute("txtZip", "");
            request.setAttribute("txtCash", "");
            request.setAttribute("txtEmail", "");
            
            
            try {
                Customer[] customers = customerDAO.getCustomers();
                request.setAttribute("customers", customers);
            } catch (DAOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            
            return successPage;

        } catch (Exception e) {
            errors.add("Unable to create new customer account");
            errors.add(e.getClass() + " - " + e.getMessage());
            errors.add(e.getStackTrace().toString());
            return originPage;
        }

    }
}